#ifndef QUERYSERIAL_H
#define QUERYSERIAL_H
#include <QObject>
#include <QSerialPort>
#include <qserialport.h>
#include <thread>
#include <mutex>
#include "CEvtVar.h"

#define SEND_BUF_MAX (1024)
class QuerySerial : public QObject
{
    Q_OBJECT
public:
    QuerySerial();
    ~QuerySerial();
    void set_params(std::string com_name, QSerialPort::BaudRate baud_rate, QSerialPort::DataBits data_bits, QSerialPort::Parity parity, QSerialPort::StopBits stop_bits, QSerialPort::FlowControl flow_control);
    
    int start();
    int stop();

    int write_buf(char *buf, int size, int timeout);
    int read_buf(char *buf, int size, int timeout);
signals:
    void sig_write_buf(char *buf, int size, int timeout);

public slots:
    void slot_write_buf(char *buf, int size, int timeout);

private:
    std::string mId_path;
    QString mName;
    QSerialPort::BaudRate mBaud_rate;
    QSerialPort::DataBits mData_bits;
    QSerialPort::Parity mParity;
    QSerialPort::StopBits mStop_bits;
    QSerialPort::FlowControl mFlow_control;

    int mSerial_open = 0;
    QSerialPort* serialPort;

    int open_serial();
    int open_serial_with_handle();
    int close_serial_with_handle();

    bool mRunnig= false;
    bool mConnect = false;
    std::thread monitor;
    void monitorThreadFun();
    int _write_buf(char *buf, int size, int timeout);

    CEvtVar evtVar;
private slots:
    void handleSerialError(QSerialPort::SerialPortError port_error);
};

#endif // QUERYSERIAL_H
